import axios from "axios";
import store from "@/store";
import { message } from "antd";

const baseUrl = "http://127.0.0.1:5000";

// axios的二次封装核心
class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      },
    };
    return config;
  }

  interceptor(instance) {
    // 添加请求拦截器
    instance.interceptors.request.use(
      function (config) {
        let token = JSON.parse(localStorage.getItem("TOKEN"));
        if (!token) {
          const state = store.getState(); // 获取 Redux 状态
          token = state.auth.token;
        }
        config.headers["Authorization"] = `Bearer ${token}`;
        return config;
      },
      function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
      }
    );

    // 添加响应拦截器
    instance.interceptors.response.use(
      function (response) {
        if (response.status === 200) {
          return response.data;
        }
        message.error("请求失败");
        return Promise.reject(new Error("请求失败"));
      },
      function (error) {
        console.error("Response Error:", error);
        message.error(
          (error.response &&
            error.response.data &&
            error.response.data.message) ||
            "服务器错误！"
        );
        return Promise.reject(error);
      }
    );
  }

  request(options) {
    options = { ...this.getInsideConfig(), ...options };
    // 创建axios实例
    const instance = axios.create();
    // 实例拦截器的绑定
    this.interceptor(instance);
    return instance(options);
  }
}

const http = new HttpRequest(baseUrl);

export default http;
